<script setup lang="ts">
defineOptions({
  name: "selfContainer"
});
import {
  getContainerDetail,
  containerLog,
  getContainerStatus,
  getContainerLog,
  getContainerList,
  getContainerPrice,
  pay_request,
  deleteConNet,
  DelHttp
} from "@/api/user";
import { useRoute, useRouter } from "vue-router";
import { onMounted, ref, reactive, watch } from "vue";
import { message } from "@/utils/message";
import { debounce } from "@pureadmin/utils";
import SetMenu from "../servers/components/SetMenu.vue";
import AddHttps from "./components/AddHttps.vue";
const route = useRoute();
const router = useRouter();
const images = ref();
onMounted(() => {
  getContainerDetail(route.query.container_id).then(res => {
    container_message.value = res.data.data;
    server.value = res.data.data.server;
    plan.value = res.data.data.plan;
    image.value = res.data.data.image;
    images.value = objectToString(res.data.data.env);
    container_connect.value = res.data.data.container_connects;
    volumes.value = res.data.data.volumes;
    console.log("获取状态", container_message.value.container_state);
    if (container_message.value.container_state > 1) {
      getStatus().catch(err => {
        container_state.value = 3;
      });
    } else {
      container_state.value = container_message.value.container_state;
    }
  });
  containerLog({
    container_id: route.query.container_id
  }).then(res => {
    containers_log.value = res.data.data;
  });
  getContainerLog({
    container_id: route.query.container_id
  }).then(res => {
    if (res.data.data.data) {
      let logs = res.data.data.data.logs;
      run_logs.value = logs.split("\\r\\n");
      run_logs.value.pop();
      run_logs.value = run_logs.value.map(log => ({ log }));
    }
  });
  getWidth();
});
const run_logs = ref([]);
const container_state = ref();
const getStatus = async () => {
  let res = await getContainerStatus({
    container_id: route.query.container_id
  });
  if (res.data.data.status == true) {
    if (res.data.data.data.state == true) {
      //开机
      container_state.value = 2;
    } else {
      //关机
      container_state.value = 3;
    }
  }
};

const container_message = ref({});
const server = ref({});
const plan = ref({});
const image = ref({});
const containers_log = ref([]);
const container_connect = ref([]);
const volumes = ref([]);
//响应式
const widthcolumn = ref(4);
const getWidth = () => {
  let screenWidth = window.innerWidth;
  if (screenWidth < 768) {
    widthcolumn.value = 2;
  } else {
    widthcolumn.value = 4;
  }
};

//网络添加
const netVisible = ref(false);
const addVisible = ref(false);
const network_list = [
  {
    value: "nginx",
    name: "建站服务"
  },
  {
    value: "port_forward",
    name: "自定义端口"
  },
  {
    value: "floating_ip",
    name: "独立ip"
  }
];
const form = reactive({
  type: "",
  container_id: "",
  server_port: "",
  container_port: "",
  domain: "",
  floating_ip: ""
});
const prot_data = ref([]);
const delProt = (index, data) => {
  message("删除成功！", { type: "success" });
  prot_data.value.splice(index, 1);
};
const addnet = data => {
  if (data.type != "") {
    const entries = Object.entries(data);
    const filteredEntries = entries.filter(([key, value]) => value !== "");
    const filteredObj = Object.fromEntries(filteredEntries);
    console.log("网络信息", container_connect.value);
    if (
      (container_connect.value.find(
        item => item.connect_type != "floating_ip"
      ) &&
        data.type == "floating_ip") ||
      (container_connect.value.find(
        item => item.connect_type == "floating_ip"
      ) &&
        data.type != "floating_ip")
    ) {
      message("独立ip不能与其他网络共存", { type: "error" });
      Object.keys(form).forEach(key => {
        form[key] = "";
      });
    } else {
      prot_data.value.push(filteredObj);
      Object.keys(form).forEach(key => {
        form[key] = "";
      });
      message("添加成功！", { type: "success" });
      addVisible.value = false;
    }
  } else {
    message("请填写完整", { type: "error" });
  }
};
const payprice = ref("");
const paylist = reactive({
  pay_type: "",
  proxy: "",
  container_id: route.query.container_id
});
const pay_src = ref("");
const pay_url = ref("");
const pay_dialog = ref(false);
//支付
const topay = () => {
  paylist.proxy = JSON.stringify(prot_data.value);
  getContainerList(paylist).then(res => {
    if (res.data.code == 200) {
      //生成订单
      pay_request({
        pay_type: res.data.data.pay_type,
        trade_id: res.data.data.trade_id
      }).then(res => {
        console.log("支付信息", res);
        if (res.data.data.type == "html") {
          pay_url.value = res.data.data.html;
          pay_dialog.value = true;
        } else if (res.data.data.type == "img") {
          pay_src.value = res.data.data.img;
        } else {
          message("支付成功", { type: "success" });
          location.reload();
        }
      });
    } else {
      message(res.data.msg, { type: "error" });
    }
  });
};
watch(
  [prot_data],
  () => {
    getpay();
  },
  { deep: true }
);
const getpay = debounce(() => {
  let objInfo = {
    container_id: route.query.container_id,
    proxy: JSON.stringify(prot_data.value)
  };
  getContainerPrice(objInfo).then(res => {
    if (res.data.code == 200) {
      payprice.value = res.data.data.price;
      payprice.value += "";
    }
  });
});
const toNext = state => {
  if (state == 0) {
    router.push("/order/orderlist");
  }
};
//未支付
const topay_dialog = ref(true);
//镜像变量
const objectToString = obj => {
  console.log("镜像信息", obj);
  obj = JSON.parse(obj);
  if (
    obj &&
    typeof obj === "object" &&
    !Array.isArray(obj) &&
    Object.keys(obj).length > 0
  ) {
    return Object.entries(obj);
  } else {
    return "";
  }
};
//删除用户网络
const delConnect = data => {
  deleteConNet({
    container_id: data.container_id,
    connect_id: data.connect_id
  }).then(res => {
    if (res.data.code == 200) {
      message("删除成功！", { type: "success" });
      getContainerDetail(route.query.container_id).then(res => {
        container_connect.value = res.data.data.container_connects;
      });
    }
  });
};
// 添加https
const httpscert = ref(false);
const infohttps = ref();
const Addhttps = (data: any) => {
  httpscert.value = true;
  infohttps.value = data;
};
const offdialog = () => {
  httpscert.value = false;
};
// 删除https
const delhttps = async (data: any) => {
  await delHttps({
    connect_id: data.connect_id,
    container_id: data.container_id
  }).then(res => {
    if (res.data.code == 200) {
      message("删除成功！", { type: "success" });
      getContainerDetail(route.query.container_id).then(res => {
        container_connect.value = res.data.data.container_connects;
      });
    }
  });
};
</script>

<template>
  <div class="body">
    <el-descriptions title="容器信息" direction="vertical" :column="widthcolumn" size="default" border>
      <el-descriptions-item label="容器 ID">{{
        container_message.container_id
        }}</el-descriptions-item>
      <el-descriptions-item label="价格">{{ container_message.pay }} 元</el-descriptions-item>
      <el-descriptions-item label="地区">{{ server.location }}/{{ server.name }}</el-descriptions-item>
      <el-descriptions-item label="服务器IP">{{
        server.server_ip
        }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">
        <el-tag size="small">{{ container_message.created_at }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="到期时间">
        <el-tag size="small">{{ container_message.become_time }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="所属套餐">{{
        plan.name
        }}</el-descriptions-item>
      <el-descriptions-item label="内存">{{ plan.memory }}MB</el-descriptions-item>
      <el-descriptions-item label="硬盘">{{ plan.disk }}GB<span v-if="container_message.volume_size > 0">+</span><el-tag
          v-if="container_message.volume_size > 0">{{ container_message.volume_size }}GB</el-tag></el-descriptions-item>
      <el-descriptions-item label="cpu">{{ plan.cpu }}毫核</el-descriptions-item>

      <el-descriptions-item label="带宽">{{ Math.floor(plan.bandwidth_tx) }}mbps/{{
        Math.floor(plan.bandwidth_rx)
      }}mbps</el-descriptions-item>
      <el-descriptions-item label="镜像">{{
        image.show_name ? image.show_name : image.name
        }}</el-descriptions-item>
      <el-descriptions-item label="容器IP">{{
        container_message.container_ip
        }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="container_state == 0 || container_state == 1
            ? 'info'
            : container_state == 2
              ? 'success'
              : 'danger'
          ">{{
            container_state == 0
              ? "未支付"
              : container_state == 1
                ? "未开通"
                : container_state == 2
                  ? "开机"
                  : "关机"
          }}</el-tag></el-descriptions-item>

      <el-descriptions-item :span="4" label="操作">
        <SetMenu v-if="container_state !== 0" :id="container_message.container_id" trade_type="container"
          :server_id="container_message.server_id" :console_url="server.console_url" @statusUpdated="getStatus" />
        <el-button v-if="container_state == 0" type="primary" @click="router.push('/order/orderlist')">支付</el-button>
      </el-descriptions-item>
      <el-descriptions-item :span="8" label="镜像变量"><el-tag v-for="item in images" v-if="images != ''"
          style="margin-right: 10px">{{ item[0] }}:{{ item[1] }}</el-tag></el-descriptions-item>
      <el-descriptions-item :span="8" label="镜像描述">
        <div class="mytitle">
          {{ image.description }}
        </div>
      </el-descriptions-item>
    </el-descriptions>

    <!-- tab栏 -->
    <el-tabs type="border-card" class="info_table">
      <el-tab-pane label="网络信息">
        <el-button type="primary" plain @click="netVisible = true">添加网络</el-button>
        <div class="table-container">
          <el-table class="table_el" :data="container_connect" style="width: auto">
            <el-table-column label="网络类型">
              <template #default="scope">
                {{
                  scope.row.connect_type == "nginx"
                    ? "建站服务"
                    : scope.row.connect_type == "floating_ip"
                      ? "独立ip"
                      : "自定义端口"
                }}
              </template>
            </el-table-column>
            <el-table-column label="外部访问端口" prop="server_port" />
            <el-table-column label="内部端口" prop="container_port" />
            <el-table-column label="域名" prop="domain" />
            <el-table-column label="浮动IP" prop="floating_ip" />
            <el-table-column label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.state == 0 ? 'info' : 'success'" @click="toNext(scope.row.state)">{{
                  scope.row.state == 0 ? "未支付" : "已支付" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="created_at" show-overflow-tooltip />
            <el-table-column label="操作">
              <template #default="scope">
                <el-row :gutter="24">
                  <el-col :span="24">
                    <el-button type="danger" plain @click="delConnect(scope.row)">删除</el-button>
                  </el-col>
                  <el-col v-if="!scope.row.ssl_cert && route.query.type == 'nginx'" :span="24">
                    <el-button type="primary" plain @click="Addhttps(scope.row)">添加https</el-button>
                  </el-col>
                  <el-col v-if="scope.row.ssl_cert && route.query.type == 'nginx'" :span="24">
                    <el-button type="danger" plain @click="delhttps(scope.row)">删除https</el-button>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-dialog v-model="netVisible" title="网络信息" draggable overflow>
        <div style="display: flex; flex-wrap: wrap">
          <el-button @click="addVisible = true">添加网络</el-button>
          <el-table class="table_el" :data="prot_data">
            <el-table-column label="网络类型">
              <template #default="scope">
                {{
                  scope.row.type == "nginx"
                    ? "建站服务"
                    : scope.row.type == "floating_ip"
                      ? "独立ip"
                      : "自定义端口"
                }}
              </template>
            </el-table-column>
            <el-table-column label="容器端口" prop="container_port" />
            <el-table-column label="域名" prop="domain" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" @click="delProt(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-form :model="paylist" label-width="100px">
            <el-form-item label="支付方式">
              <el-checkbox label="优先使用余额支付" checked disabled />
              <el-radio v-model="paylist.pay_type" :value="0" size="large">支付宝
              </el-radio>
              <el-radio v-model="paylist.pay_type" :value="1" size="large">微信</el-radio>
            </el-form-item>
            <el-form-item v-if="pay_src != ''" label="扫码支付">
              <el-image style="width: 100px; height: 100px" :src="pay_src" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="pay_money">
            <el-statistic title="总计结算金额：" :value="payprice != '' ? payprice + '元' : '- -' + ' 元'" suffix="">
              <template #suffix>
                <el-icon style="vertical-align: -20px">
                  <ChatLineRound />
                </el-icon>
              </template>
            </el-statistic>
          </div>
          <div class="dialog-footer">
            <el-button @click="netVisible = false">关闭</el-button>
            <el-button type="primary" :disabled="payprice == '' ? true : false" @click="topay">提交订单
            </el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog v-model="addVisible" title="添加网络">
        <div>
          <el-form :model="form" label-width="auto" style="max-width: 600px">
            <el-form-item label="网络类型">
              <el-select v-model="form.type" placeholder="请选择" style="width: 240px">
                <el-option v-for="item in network_list" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.type == 'port_forward' || form.type == 'nginx'" label="容器内部端口号" :rules="[
              {
                required: true,
                message: '请输入容器内部端口号',
                trigger: 'blur'
              }
            ]">
              <el-input v-model="form.container_port" type="number" :min="1" :max="65535"
                placeholder="端口号应在1-65535之间" />
            </el-form-item>
            <el-form-item v-if="form.type == 'nginx'" label="域名">
              <el-input v-model="form.domain" />
            </el-form-item>
          </el-form>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="addVisible = false">关闭</el-button>
            <el-button type="primary" @click="addnet(form)">添加</el-button>
          </div>
        </template>
      </el-dialog>

      <el-tab-pane label=" 数据卷信息">
        <el-table class="table_el" :data="volumes" style="width: auto">
          <el-table-column label="ID" prop="volume_id" />
          <el-table-column label="空间大小" prop="size" />
          <el-table-column label="挂载路径" prop="mount_path" />
          <el-table-column label="创建时间" prop="created_at" />
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="操作日志">
        <div class="table-container">
          <el-table :data="containers_log" style="width: 100%">
            <el-table-column prop="created_at" label="时间" />
            <el-table-column prop="action_info" label="日志" />
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="运行日志">
        <div class="table-container">
          <el-table :data="run_logs" style="width: 100%">
            <el-table-column label="运行" prop="log" />
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-model="pay_dialog" title="支付" style="width: 90%; height: 1000px">
      <iframe :srcdoc="pay_url" frameborder="0" style="width: 100%; height: 800px" />
    </el-dialog>
    <el-dialog v-if="container_state == 0" v-model="topay_dialog" title="未支付" style="width: 50%; height: 50%"
      :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <p>当前容器订单未支付，请前往支付！</p>
      <a style="text-decoration: underline; color: #409eff" @click="router.push('/order/orderlist')">点击前往支付</a>
    </el-dialog>
    <el-dialog v-model="httpscert" title="请填写信息" width="800" align-center>
      <AddHttps :info="infohttps" @off="offdialog" />
    </el-dialog>
  </div>
</template>

<style scoped>
.el-descriptions {
  margin-top: 20px;
}

.info_table {
  margin: 20px 0;
}

.table-container {
  /* 添加滚动条 */
  overflow-y: auto;
  /* 设置最大高度，超出后会出现滚动条 */
  max-height: 320px;
}

:deep(.el-col) {
  margin-top: 5px;
}

.mytitle {
  max-width: 800px;
  overflow: hidden;
  word-break: break-all;
  word-wrap: break-word;
  white-space: pre-wrap;
}
</style>
